package starter.kit.rx.app.feature.main;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.RadioGroup;

import com.bilibili.magicasakura.utils.ThemeUtils;
import com.bilibili.magicasakura.widgets.TintToolbar;
import com.mikepenz.fontawesome_typeface_library.FontAwesome;
import com.mikepenz.materialdrawer.AccountHeader;
import com.mikepenz.materialdrawer.AccountHeaderBuilder;
import com.mikepenz.materialdrawer.Drawer;
import com.mikepenz.materialdrawer.DrawerBuilder;
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem;
import com.mikepenz.materialdrawer.model.ProfileDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IProfile;

import butterknife.BindView;
import starter.kit.feature.rx.RxStarterActivity;
import starter.kit.rx.app.R;
import starter.kit.rx.app.feature.auth.LoginActivity;
import starter.kit.rx.app.feature.book.BookFragment;
import starter.kit.rx.app.feature.content.ContentActivity;
import starter.kit.rx.app.feature.film.FilmFragment;
import starter.kit.rx.app.feature.music.MusicFragment;
import starter.kit.rx.app.feature.util.RxPreferencesActivity;
import starter.kit.rx.app.feature.util.SimpleHudActivity;
import starter.kit.rx.app.util.ThemeHelper;
import starter.kit.rx.app.views.ThemePickDialog;

public class MainActivity extends RxStarterActivity implements Drawer.OnDrawerItemClickListener, ThemePickDialog.ClickListener {

    //save our header or result
    private AccountHeader headerResult = null;
    private Drawer result = null;
    @BindView(R.id.toolbar)
    TintToolbar mToolbar;
    @BindView(R.id.viewPager)
    ViewPager mViewPager;
    @BindView(R.id.radiogroup)
    RadioGroup radioGroup;

    private int currentFragment;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        setupToolbar();
        setupDrawer(savedInstanceState);
        setupViewPager();
        setupListener();
    }


    private void setupToolbar() {
        setSupportActionBar(mToolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayShowTitleEnabled(false);
//      getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//      getSupportActionBar().setTitle(R.string.app_name);
        }
    }

    private void setupDrawer(Bundle savedInstanceState) {
        // Create a few sample profile
        // NOTE you have to define the loader logic too. See the CustomApplication for more details
        final IProfile profile = new ProfileDrawerItem().withName("Smartydroid")
                .withEmail("smartydroid@gmail.com")
                .withIcon("https://avatars2.githubusercontent.com/u/13810934?v=3&s=460");

        // Create the AccountHeader
        headerResult = new AccountHeaderBuilder().withActivity(this)
                .withHeaderBackground(R.drawable.header)
                .addProfiles(profile)
                .withSavedInstance(savedInstanceState)
                .build();

        //Create the drawer
        result = new DrawerBuilder().withActivity(this)
                .withToolbar(mToolbar)
                .withHasStableIds(true)
                .withAccountHeader(headerResult) //set the AccountHeader we created earlier for the header
                .addDrawerItems(
                        new PrimaryDrawerItem().withName("主页").withIcon(FontAwesome.Icon.faw_android).withTag(TAG_FEEDS),
                        new PrimaryDrawerItem().withName("Login").withIcon(FontAwesome.Icon.faw_adjust).withTag(TAG_LOGIN),
                        new PrimaryDrawerItem().withName("SimpleHud").withIcon(FontAwesome.Icon.faw_adjust).withTag(TAG_SIMPLE_HUD),
                        new PrimaryDrawerItem().withName("Content").withIcon(FontAwesome.Icon.faw_connectdevelop).withTag(TAG_CONTENT),
                        new PrimaryDrawerItem().withName("主题").withIcon(FontAwesome.Icon.faw_paint_brush).withTag(TAG_THEME)
                )
                .addStickyDrawerItems(
                        new PrimaryDrawerItem().withName(R.string.drawer_item_settings).withIcon(FontAwesome.Icon.faw_cog).withTag(TAG_SETTING),
                        new PrimaryDrawerItem().withName(R.string.drawer_item_open_source).withIcon(FontAwesome.Icon.faw_github)
                )
                .withOnDrawerItemClickListener(this)
                .withSavedInstance(savedInstanceState)
                .withShowDrawerOnFirstLaunch(false)
                .build();
    }

    private void setupViewPager() {
        MainPagerAdapter adapter = new MainPagerAdapter(getSupportFragmentManager());

        adapter.addFrag(FilmFragment.newInstance());
        adapter.addFrag(BookFragment.newInstance());
        adapter.addFrag(MusicFragment.newInstance());

        mViewPager.setAdapter(adapter);
        mViewPager.setOnPageChangeListener(onPageChangeListener);
        mViewPager.setOffscreenPageLimit(3);
    }

    private void setupListener() {
        radioGroup.setOnCheckedChangeListener((group, checkedId) -> {

            switch (checkedId) {
                case R.id.rb_home:
                    currentFragment = 0;
                    break;
                case R.id.rb_dynamic:

                    currentFragment = 1;

                    break;
                case R.id.rb_message:
                    currentFragment = 2;
                    break;

            }
            mViewPager.setCurrentItem(currentFragment);
        });
    }


    private static final String TAG_FEEDS = "feeds";
    private static final String TAG_LOGIN = "login";
    private static final String TAG_SIMPLE_HUD = "SimpleHud";
    private static final String TAG_CONTENT = "ContentDemo";
    private static final String TAG_THEME = "theme";
    private static final String TAG_SETTING = "setting";

    @Override
    public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
        if (TAG_LOGIN.equals(drawerItem.getTag())) {
            startActivity(new Intent(MainActivity.this, LoginActivity.class));
            return true;
        }
        if (TAG_SIMPLE_HUD.equals(drawerItem.getTag())) {
            startActivity(new Intent(MainActivity.this, SimpleHudActivity.class));
            return true;
        }
        if (TAG_CONTENT.equals(drawerItem.getTag())) {
            startActivity(new Intent(MainActivity.this, ContentActivity.class));
            return true;
        }
        if (TAG_THEME.equals(drawerItem.getTag())) {
            showThemeDialog();
            return false;
        }
        if (TAG_SETTING.equals(drawerItem.getTag())) {
            startActivity(new Intent(MainActivity.this, RxPreferencesActivity.class));
            return true;
        }
        return false;
    }

    /**
     * 显示颜色选择框的
     */
    private void showThemeDialog() {
        ThemePickDialog dialog = new ThemePickDialog();
        dialog.setClickListener(this);
        dialog.show(getSupportFragmentManager(), ThemePickDialog.TAG);
    }




    @Override
    public void onConfirm(int currentTheme) {
        if (ThemeHelper.getTheme(MainActivity.this) != currentTheme) {
            ThemeHelper.setTheme(MainActivity.this, currentTheme);
            ThemeUtils.refreshUI(MainActivity.this, new ThemeUtils.ExtraRefreshable() {
                        @Override
                        public void refreshGlobal(Activity activity) {
                            //for global setting, just do once
                            if (Build.VERSION.SDK_INT >= 21) {
                                final MainActivity context = MainActivity.this;
                                ActivityManager.TaskDescription taskDescription = new ActivityManager.TaskDescription(null, null, ThemeUtils.getThemeAttrColor(context, android.R.attr.colorPrimary));
                                setTaskDescription(taskDescription);
                                getWindow().setStatusBarColor(ThemeUtils.getColorById(context, R.color.theme_color_primary_dark));
                            }
                        }

                        @Override
                        public void refreshSpecificView(View view) {
                            //TODO: will do this for each traversal
                        }
                    }
            );
        }
    }



    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //add the values which need to be saved from the drawer to the bundle
        outState = result.saveInstanceState(outState);
        //add the values which need to be saved from the accountHeader to the bundle
        outState = headerResult.saveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onBackPressed() {
        //handle the back press :D close the drawer first and if the drawer is closed close the activity
        if (result != null && result.isDrawerOpen()) {
            result.closeDrawer();
        } else {
            super.onBackPressed();
        }
    }

    private ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            switch (position) {
                case 0:
                    radioGroup.check(R.id.rb_home);
                    break;
                case 1:
                    radioGroup.check(R.id.rb_dynamic);
                    break;
                case 2:
                    radioGroup.check(R.id.rb_message);
                    break;
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    };


}
